package cn.jingyuan.owl.json.fastjson.serializable;

import cn.jingyuan.owl.enums.core.EnumInteger;
import cn.jingyuan.owl.enums.core.EnumString;
import com.alibaba.fastjson.annotation.JSONType;
import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.parser.deserializer.ObjectDeserializer;

import java.lang.reflect.Type;

public class ExtendParserConfig extends ParserConfig {

    public static final ExtendParserConfig INSTANCE = new ExtendParserConfig();

    public static ParserConfig getInstance() {
        return INSTANCE;
    }

    @Override
    public ObjectDeserializer getDeserializer(Class<?> clazz, Type type) {
        ObjectDeserializer deserializer;
        if (clazz.isEnum()) {
            JSONType jsonType = clazz.getAnnotation(JSONType.class);

            if (null != jsonType) {
                Class<?> aClass = jsonType.deserializer();
                try {
                    deserializer = (ObjectDeserializer) aClass.newInstance();
                    this.putDeserializer(type, deserializer);

                    return deserializer;
                } catch (Throwable error) {
                    // skip
                }
            } else {
                if (EnumHelper.existEnumCoreClass()) {
                    if (EnumString.class.isAssignableFrom(clazz)) {
                        deserializer = EnumStringSerializer.INSTANCE;

                        return deserializer;
                    }

                    if (EnumInteger.class.isAssignableFrom(clazz)) {
                        deserializer = EnumIntegerSerializer.INSTANCE;

                        return deserializer;
                    }
                }
            }
        }

        return super.getDeserializer(clazz, type);
    }

}
